import { Sprite } from 'pixi.js';
import BaseSprite from './BaseSprite.js';
import ResourceManager from '../resource.js';

class CloudSprite extends BaseSprite {
    constructor(app) {
        super(app, 'clouds');
        
        this.cloudItems = [];
        this.width = 160;
        this.height = 120;
        this.speed = 0.5;
        
        this.resources = {
            cloud: './cloud.png'
        };
        
        this.cloudConfigs = [
            {
                width: this.width,
                height: this.height,
                x: 0,
                y: 240,
            },
            {
                width: this.width,
                height: this.height,
                x: 640,
                y: 60,
            }
        ];
    }

    async loadResources() {
        for (const [name, url] of Object.entries(this.resources)) {
            await ResourceManager.load(name, url);
        }
    }

    async init() {
        const texture = ResourceManager.get('cloud');
        
        for (const config of this.cloudConfigs) {
            const cloud = new Sprite(texture);
            this.cloudItems.push(cloud);
            cloud.anchor.set(0.5);
            cloud.width = this.width;
            cloud.height = this.height;
            cloud.x = config.x;
            cloud.y = config.y;
            this.addSprite(cloud);
        }
    }

    update(deltaTime) {
        if (!this.active) return;
        
        this.updateClouds(deltaTime);
    }

    updateClouds(deltaTime) {
        if (this.cloudItems[0].x > 640 + this.width / 2) {
            this.cloudItems[0].x = 0 - this.width / 2;
        } else {
            this.cloudItems[0].x = this.cloudItems[0].x + this.speed * deltaTime;
        }

        if (this.cloudItems[1].x < -this.width / 2) {
            this.cloudItems[1].x = 640 + this.width / 2;
        } else {
            this.cloudItems[1].x = this.cloudItems[1].x - this.speed * deltaTime;
        }
    }

    destroy() {
        this.cloudItems = [];
        super.destroy();
    }
}

export default CloudSprite;
